@tool
extends TileMap

@export var isGenerate: bool
@export var isClear: bool

@export_group('地形配置')
@export_range(-1, 1, 0.01) var grass
@export_range(-1, 1, 0.01) var dirty
@export_range(-1, 1, 0.01) var sand

@export var mapSeed: int

# 地图里水平与垂直的格子数量
@export var width := 20
@export var height := 20

func _physics_process(_delta):
	if isGenerate:
		isGenerate = false
		renderMap()

	if isClear:
		isClear = false
		clear()

var layer = 0
var sourceId = 0

# 渲染图块
func renderMap():
	var noise = FastNoiseLite.new()
	noise.noise_type = FastNoiseLite.TYPE_CELLULAR

	var rand = RandomNumberGenerator.new()
	if mapSeed != 0: noise.seed = mapSeed
	else: noise.seed = rand.randi()

	for x in range( - width, width):
		for y in range( - height, height):
			var noiseVal = noise.get_noise_2d(x, y)
			var crood = Vector2i(0, 1)

			if noiseVal >= grass: crood = Vector2i(0, 0)
			elif noiseVal >= dirty: crood = Vector2i(9, 4)
			elif noiseVal >= sand: crood = Vector2i(9, 16)

			set_cell(layer, Vector2i(x, y), sourceId, crood)